// 存放的是 profile 相关的请求action

import { ApiResponse, User, UserProfile } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import http from '@/utils/request'
import { removeToken } from '@/utils/token'

// 用于创建 请求个人信息的action
export function userActionCreator(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<User>>('/user')
    // console.log(res)

    dispatch({
      type: 'profile/set_user',
      payload: res.data.data,
    } as RootAction)
  }
}

export function userProfileActionCreator(): RootThunkAction {
  return async (dispatch) => {
    // 发请求
    const res = await http.get<ApiResponse<UserProfile>>('/user/profile')
    // console.log(res)

    dispatch({
      type: 'profile/set_user_profile',
      payload: res.data.data,
    } as RootAction)
  }
}

// 已知的类型每个属性都变为可选的 Partial<T>

export function updateProfileActionCreator(
  data: Partial<UserProfile>
): RootThunkAction {
  return async (dispatch) => {
    //  /user/profile patch { intro: '不错' } { name: '张三' }
    // 1.发请求更新数据
    await http.patch('/user/profile', data)
    // console.log(res)
    // 2.发请求获取最新的数据存入redux
    await dispatch(userProfileActionCreator())
  }
}

export function updatePhotoActionCreator(data: FormData): RootThunkAction {
  return async (dispatch) => {
    // 1.更新头像
    await http.patch('/user/photo', data)
    // console.log(res)
    // 2.获取新的用户信息 存入redux
    await dispatch(userProfileActionCreator())
  }
}

// 函数用于创建 清除所有信息的action
export default function logoutActionCreator(): RootThunkAction {
  return async (dispatch) => {
    // 清除token（仓库，本地）  清除用户资料（基本 详情）
    removeToken()

    dispatch({
      type: 'login/login',
      payload: {},
    } as RootAction)

    dispatch({
      type: 'profile/set_user',
      payload: {},
    } as RootAction)

    dispatch({
      type: 'profile/set_user_profile',
      payload: {},
    } as RootAction)
  }
}
